/*
 * 附件上传配置
 * @Description: Jishupu-Admin
 * @Author: 技术铺<jishupu@qq.com>
 * @Date: 2021-11-30
 *
 */
import { getToken } from '@/utils/auth'
import { config } from '@/api/attachment'
import i18n from '@/lang' // 多语言支持

const state = {
}

const mutations = {
  SET_CONFIG: (state, items) => {
    state.headers = { Authorization: `Bearer ${getToken()}` } // 头设置
    state.action = process.env.VUE_APP_BASE_API + '/v1/attachment/upload' // 单文件上传地址
    state.imageAction = process.env.VUE_APP_BASE_API + '/v1/attachment/upload-image' // 图片上传地址
    state.mediaAction = process.env.VUE_APP_BASE_API + '/v1/attachment/upload-media' // 音视频上传地址
    state.multipleAction = process.env.VUE_APP_BASE_API + '/v1/attachment/multiple-upload' // 多文件上传地址
    state.allowTypeList = items.allowTypeList ?? '' // 允许上传附件类型
    state.allowSize = items.allowSize ?? 0 // 允许上传附件大小
    state.allowImageTypeList = items.allowImageTypeList ?? '' // 允许上传图片附件类型
    state.allowImageSize = items.allowImageSize ?? 0 // 允许上传图片附件大小
    state.allowMediaTypeList = items.allowMediaTypeList ?? '' // 允许上传音视频类型
    state.allowMediaSize = items.allowMediaSize ?? 0// 允许上传音视频大小

    // 文本描述
    const upload_requirements = i18n.t('attachment.upload_requirements')
    const upload_type = i18n.t('attachment.upload_type')
    const disabled = i18n.t('attachment.disabled')
    const upload_size = i18n.t('attachment.upload_size')
    const not_limited = i18n.t('attachment.not_limited')
    const default_allowSize = state.allowSize > 0 ? state.allowSize + 'MB' : not_limited
    state.defaultUploadRequirementsTips = upload_requirements + upload_type + '：' + (state.allowTypeList.length === 0 ? disabled : state.allowTypeList) + '；' + upload_size + '：' + default_allowSize
    state.imageUploadRequirementsTips = upload_requirements + upload_type + '：' + (!state.allowImageTypeList ? disabled : state.allowImageTypeList) + '；' + upload_size + '：' + (state.allowImageSize > 0 ? state.allowImageSize + 'MB' : default_allowSize)
    state.mediaUploadRequirementsTips = upload_requirements + upload_type + '：' + (!state.allowMediaTypeList ? disabled : state.allowMediaTypeList) + '；' + upload_size + '：' + (state.allowMediaSize > 0 ? state.allowMediaSize + 'MB' : default_allowSize)
  }
}

const actions = {
  // 设置数据字典
  addConfig({ commit }) {
    return new Promise((resolve, reject) => {
      config().then(response => {
        const data = response.data
        commit('SET_CONFIG', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 移除数据字典
  delConfig({ commit }) {
    return new Promise(resolve => {
      commit('SET_CONFIG', {})
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
